﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2016, Outcoder. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>$CreationDate$</CreationDate>
</File>
*/
#endregion

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

using Outcoder.ComponentModel;

namespace Outcoder.Collections
{
	public class AdaptiveCollection<T, TInner> : ObservableCollection<T>, IDisposable
		where T : class, IAttachObject<TInner>, new()
	{
		readonly Dictionary<TInner, T> lookupDictionary
			= new Dictionary<TInner, T>();

		readonly ObservableCollection<TInner> monitoredCollection;
		public ObservableCollection<TInner> MonitoredCollection => monitoredCollection;

		bool ignoreChanges;

		public AdaptiveCollection(ObservableCollection<TInner> monitoredCollection)
		{
			ArgumentValidator.AssertNotNull(monitoredCollection, "commandCollection");

			this.monitoredCollection = monitoredCollection;
			monitoredCollection.CollectionChanged += OnCollectionChanged;

			try
			{
				ignoreChanges = true;

				foreach (var command in monitoredCollection)
				{
					var attacher = new T();
					attacher.AttachObject(command);
					lookupDictionary[command] = attacher;

					base.Add(attacher);
				}
			}
			finally
			{
				ignoreChanges = false;
			}
		}

		void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (ignoreChanges)
			{
				return;
			}

			NotifyCollectionChangedAction action = e.Action;

			if (action == NotifyCollectionChangedAction.Add)
			{
				var list = new List<T>();

				foreach (TInner command in e.NewItems)
				{
					var attacher = new T();
					attacher.AttachObject(command);
					lookupDictionary[command] = attacher;
					list.Add(attacher);
				}

				AddRangeInternal(list);
			}
			else if (action == NotifyCollectionChangedAction.Move)
			{
				int movedFromIndex = e.OldStartingIndex;
				int movedToIndex = e.NewStartingIndex;

				try
				{
					ignoreChanges = true;
					base.MoveItem(movedFromIndex, movedToIndex);
				}
				finally
				{
					ignoreChanges = false;
				}

			}
			else if (action == NotifyCollectionChangedAction.Remove)
			{
				var oldItems = e.OldItems;

				var itemsToRemove = new List<T>();

				foreach (TInner oldItem in oldItems)
				{
					T owner;

					if (lookupDictionary.TryGetValue(oldItem, out owner) && owner != null)
					{
						itemsToRemove.Add(owner);
					}

					lookupDictionary.Remove(oldItem);
				}

				foreach (var owner in itemsToRemove)
				{
					try
					{
						ignoreChanges = true;
						base.Remove(owner);
					}
					finally
					{
						ignoreChanges = false;
					}

					owner.DetachObject();

					var disposable = owner as IDisposable;

					if (disposable != null)
					{
						disposable.Dispose();
					}

				}
			}
			else if (action == NotifyCollectionChangedAction.Replace)
			{
				var removedItems = e.OldItems;

				var itemsToRemove = new List<T>();

				foreach (TInner oldItem in removedItems)
				{
					T owner;

					if (lookupDictionary.TryGetValue(oldItem, out owner) && owner != null)
					{
						itemsToRemove.Add(owner);
					}

					lookupDictionary.Remove(oldItem);
				}

				foreach (var owner in itemsToRemove)
				{
					try
					{
						ignoreChanges = true;
						base.Remove(owner);
					}
					finally
					{
						ignoreChanges = false;
					}

					owner.DetachObject();

					var disposable = owner as IDisposable;

					if (disposable != null)
					{
						disposable.Dispose();
					}
				}

				var newItems = e.NewItems;
				foreach (TInner command in newItems)
				{
					var index = monitoredCollection.IndexOf(command);

					var attacher = new T();
					attacher.AttachObject(command);
					lookupDictionary[command] = attacher;

					try
					{
						ignoreChanges = true;
						base.Insert(index, attacher);
					}
					finally
					{
						ignoreChanges = false;
					}
				}
			}
			else if (action == NotifyCollectionChangedAction.Reset)
			{
				var list = new List<T>(Items);

				try
				{
					ignoreChanges = true;
					base.Clear();
				}
				finally
				{
					ignoreChanges = false;
				}

				foreach (var owner in list)
				{
					if (owner == null)
					{
						continue;
					}

					owner.DetachObject();

					var disposable = owner as IDisposable;

					if (disposable != null)
					{
						disposable.Dispose();
					}
				}

				lookupDictionary.Clear();

				var tempList = new List<T>();
				foreach (var command in monitoredCollection)
				{
					var attacher = new T();
					attacher.AttachObject(command);
					lookupDictionary[command] = attacher;

					tempList.Add(attacher);
				}

				try
				{
					ignoreChanges = true;
					foreach (var item in tempList)
					{
						base.Add(item);
					}
				}
				finally
				{
					ignoreChanges = false;
				}

			}
		}

		public void AddRange(IEnumerable<T> range)
		{
			// ReSharper disable PossibleMultipleEnumeration
			ArgumentValidator.AssertNotNull(range, "range");


			foreach (var item in range)
			{
				Add(item);
			}
			// ReSharper restore PossibleMultipleEnumeration
		}

		void AddRangeInternal(IEnumerable<T> range)
		{
			try
			{
				ignoreChanges = true;

				foreach (var item in range)
				{
					base.InsertItem(Count, item);
				}
			}
			finally
			{
				ignoreChanges = false;
			}
		}

		public new void Add(T item)
		{
			ArgumentValidator.AssertNotNull(item, "item");

			TInner obj = item.GetObject();
			if (obj == null)
			{
				throw new Exception("Item must have an existing attached object to insert into an AdaptiveCollection.");
			}

			try
			{
				ignoreChanges = true;

				monitoredCollection.Add(obj);
				base.InsertItem(base.Count, item);
			}
			finally
			{
				ignoreChanges = false;
			}


		}

		protected override void InsertItem(int index, T item)
		{
			ArgumentValidator.AssertNotNull(item, "item");

			if (ignoreChanges)
			{
				base.InsertItem(index, item);
				return;
			}

			TInner obj = item.GetObject();
			if (obj == null)
			{
				throw new Exception("Item must have an existing attached object to insert into an AdaptiveCollection.");
			}

			try
			{
				ignoreChanges = true;

				monitoredCollection.Insert(index, obj);
			}
			finally
			{
				ignoreChanges = false;
			}

			base.InsertItem(index, item);

		}

		protected override void ClearItems()
		{
			if (ignoreChanges)
			{
				base.ClearItems();
				return;
			}

			try
			{
				ignoreChanges = true;

				monitoredCollection.Clear();
			}
			finally
			{
				ignoreChanges = false;
			}

			base.ClearItems();
		}

		protected override void MoveItem(int oldIndex, int newIndex)
		{
			if (ignoreChanges)
			{
				base.MoveItem(oldIndex, newIndex);
				return;
			}

			monitoredCollection.Move(oldIndex, newIndex);
		}

		protected override void RemoveItem(int index)
		{
			if (ignoreChanges)
			{
				base.RemoveItem(index);
				return;
			}

			monitoredCollection.RemoveAt(index);
		}

		protected override void SetItem(int index, T item)
		{
			if (ignoreChanges)
			{
				base.SetItem(index, item);
				return;
			}

			TInner obj = item.GetObject();
			if (obj == null)
			{
				throw new Exception("Item must have an existing attached object to insert into an AdaptiveCollection.");
			}

			try
			{
				ignoreChanges = true;

				monitoredCollection[index] = obj;
			}
			finally
			{
				ignoreChanges = false;
			}

			base.SetItem(index, item);
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				/* Free managed resources. */

				var collection = monitoredCollection;
				if (collection != null)
				{
					collection.CollectionChanged -= OnCollectionChanged;
				}

				var lookup = lookupDictionary;
				if (lookup != null)
				{
					lookup.Clear();
				}

				Clear();
			}

			/* Free native resources if there are any. */
		}
	}
}